package com.lhf.warnsend.warnsendjson.message.util;

import sun.misc.BASE64Encoder;

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * <p></p>
 *
 * @author liuhf
 * @createTime 2021/9/3 10:07
 * @since 1.0
 */
public class AesCiphertext implements Ciphertext {

    private String key;

    public AesCiphertext(String key) {
        this.key = key;
    }

    @Override
    public String encryption(String source)  {
        Cipher cipher = null;
        byte[] sourceBytes = null;
        String content = null;
        try {
            //GPU早秘钥生成器 指定算法为AES
            KeyGenerator instance = KeyGenerator.getInstance("AES");
            instance.init(256, new SecureRandom(key.getBytes(StandardCharsets.UTF_8)));
            SecretKey secretKey = instance.generateKey();
            byte[] bytes = secretKey.getEncoded();
            SecretKeySpec keySpec = new SecretKeySpec(bytes, "AES");
            cipher = Cipher.getInstance("AES");
            sourceBytes = source.getBytes(StandardCharsets.UTF_8);
            cipher.init(Cipher.ENCRYPT_MODE, keySpec);
            byte[] aFinal = cipher.doFinal(sourceBytes);
            content = new BASE64Encoder().encode(aFinal);
        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            e.printStackTrace();
        }
        return content;

    }

    @Override
    public String decrypt(String ciphertext) {
        return null;
    }
}
